package database;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ConnectionDB {

    private final int numberRetries = 3;    
    private Connection connection;
    private Statement  statement;


    public ConnectionDB(Connection connection) {
        this.connection = connection;
    }


    public ResultSet executeSelect(String query)
            throws SQLException{
        
        int num = 0;
       StringBuilder errorMessage = new StringBuilder();

        while(num < numberRetries){
            try {
                
                statement = connection.createStatement();
                return statement.executeQuery(query);

            } catch (SQLException ex) {
                 num++;
                 errorMessage.append("Error ConnectionDB("+num+"):"+ex.getMessage()+"\n");
            }
        }

        throw new SQLException(errorMessage.toString());
    }


    public void executeUpdate(String query)
            throws SQLException {
        
        int num = 0;
       StringBuilder errorMessage = new StringBuilder();

        while(num < numberRetries){
            try {

                    statement = connection.createStatement();
                    statement.executeUpdate(query);
                    statement.close();
                    return;

            } catch (SQLException ex) {
                 num++;
                 errorMessage.append("Error ConnectionDB("+num+"):"+ex.getMessage()+"\n");
            }
        }

        throw new SQLException(errorMessage.toString());
    }


    public void closeStatement()
            throws SQLException {
                     if (statement != null) {
                        statement.close();
                        statement = null;
                     }
    }

    
    public void close()
            throws SQLException {
        if (connection != null) {
            connection.close();
        }
    }
    
}

